

Listing 1: 
Idisposable Gives You Code For All Seasons
A little extra work can make your code a lot more robust. This LogFile class frees the stream used to write to disk by implementing the IDisposable interface. It may seem a lot just to close a stream but this mechanism gives you versatility because it's been developed to be compatible with a variety of scenarios.

Public Class LogFile
	Implements IDisposable
	Private Disposed As Boolean = False
	Dim F As IO.StreamWriter
	Public Sub New(ByVal FileName As String)
		MyBase.new()
		F = New IO.StreamWriter(FileName, _
			IO.FileMode.Append)
	End Sub
	Public Sub WriteMsg(ByVal Msg As String)
		F.WriteLine(Msg)
	End Sub
	Public Overloads Sub Close() _
		Implements IDisposable.Dispose
' Call dispose indicating it's beeing called by user code
		Dispose(True)
' Tell the GC that it does not need to call Finalize
		GC.SuppressFinalize(Me)
	End Sub
	Protected Overridable Overloads Sub Dispose(ByVal _
		Disposing As Boolean)
' Check to see if Dispose has already been called.
		If Not (Me.Disposed) Then
' If disposing equals true, dispose all managed and
' unmanaged resources
' If it's false, dispose of only unmanaged resources
			If (Disposing) Then
' Dispose of managed resources.
' You can't refer to managed resources outside
' this if statement because the order in which objects 
' are finalized is not defined and you may end up 
' calling an object that has already been disposed of
			F.Close()
			End If
		End If
		Me.Disposed = True
	End Sub
	Protected Overrides Sub Finalize()
' Call dispose indicating it's beeing called by the GC 
		' so it does not dispose managed resources
		Dispose(False)
	End Sub
' This is a shared message that may be called in case you 
' just want to write a line and then close the file
	Public Shared Sub WriteLogMsg(ByVal FileName As String, ByVal Msg As String)
		Dim T As New LogFile(FileName)
		Try
			T.WriteMsg(Msg)
		Finally
			T.Close()
		End Try
	End Sub
End Class

Listing 2: 
A Little Inheritance Goes A Long Way
This is a template for a class derived from the LogFile in Listing 1. You have to implement the protected version of Dispose only if you introduce any new managed or unmanaged resources. Finalize and the public Dispose (or Close) are inherited and don't need to be implemented in the derived class.

Public Class LogFileTS
	Inherits LogFile
	Public Sub New(ByVal FileName As String)
		MyBase.new(FileName)
	End Sub
	Public Sub WriteMsgTS(ByVal Msg As String)
		WriteMsg(Now & " - " & Msg)
	End Sub
	Private disposed As Boolean = False
	Protected Overloads Overrides Sub Dispose(ByVal _
		disposing As Boolean)
		If Not (Me.disposed) Then
			Try
				If disposing Then
' Release the managed resources we may have added
				End If
' Release the unmanaged resources we may have added
				Me.disposed = True
			Finally
' Call Dispose on your our class.
				MyBase.Dispose(disposing)
			End Try
		End If
	End Sub
End Class

